package org.fw.little.base.boot;

import java.io.File;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;

import io.undertow.Handlers;
import io.undertow.Undertow;
import io.undertow.server.handlers.PathHandler;
import io.undertow.server.handlers.resource.FileResourceManager;
import io.undertow.servlet.Servlets;
import io.undertow.servlet.api.DeploymentInfo;
import io.undertow.servlet.api.DeploymentManager;
import io.undertow.servlet.api.FilterInfo;


public class UndertowStart 
{
	private String confClass;
	
	/**
	 * 端口
	 * **/
	private int port;
	
	/**
	 * 站点个根目录
	 * **/
	private String pub;
	
	/**
	 * 过滤器
	 * **/
	private Class<? extends Filter> filter;
	
	/**
	 * 欢迎页面
	 * **/
	private String[] welcomeFiles;
	
	public UndertowStart(){}

	/**
	 * 设置配置文件
	 * **/
	public void setConfClass(String confClass) 
	{
		this.confClass = confClass;
	}

	/**
	 * 端口
	 * **/
	public void setPort(int port)
	{
		this.port = port;
	}

	/**
	 * 站点根目录
	 * **/
	public void setPub(String pub)
	{
		this.pub = pub;
	}
	
	/**
	 * 欢迎页列表
	 * **/
	public void setWelcomeFiles(String[] welcomeFiles)
	{
		this.welcomeFiles = welcomeFiles;
	}
	
	/**
	 * 设置过滤器
	 * **/
	public void setFilter(Class<? extends Filter> filter)
	{
		this.filter = filter;
	}

	public void run()
	{	
		//过滤器
		FilterInfo filter = new FilterInfo("root",this.filter);
		filter.addInitParam("configClass", confClass);

		//部署单位
		DeploymentInfo rootDeployment = Servlets.deployment();
		rootDeployment.setClassLoader(UndertowStart.class.getClassLoader());
		rootDeployment.setContextPath("/");
		rootDeployment.setDeploymentName("root");
		rootDeployment.addFilter(filter);
		rootDeployment.addWelcomePages(welcomeFiles);
		rootDeployment.setEagerFilterInit(true);
		rootDeployment.setResourceManager(new FileResourceManager(new File(pub), 0));
		
		rootDeployment.addFilterUrlMapping("root", "/*", DispatcherType.ASYNC);
		rootDeployment.addFilterUrlMapping("root", "/*", DispatcherType.ERROR);
		rootDeployment.addFilterUrlMapping("root", "/*", DispatcherType.FORWARD);
		rootDeployment.addFilterUrlMapping("root", "/*", DispatcherType.INCLUDE);
		rootDeployment.addFilterUrlMapping("root", "/*", DispatcherType.REQUEST);

		//部署包加入容器
		DeploymentManager rootDeploymentManage = Servlets.defaultContainer().addDeployment(rootDeployment);
		rootDeploymentManage.deploy();

		try
		{
			PathHandler path = Handlers.path().addPrefixPath("/", rootDeploymentManage.start());
			Undertow server  = Undertow.builder().addHttpListener(port,"0.0.0.0").setHandler(path).setDirectBuffers(true).build();
			server.start();
		}
		catch(Exception exe)
		{
			exe.printStackTrace();
		}
	}
}